package com.itboye.sunsunhome.www.aq;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.itboye.base.BaseActivity;
import com.itboye.sunsun.utils.LoweImageView;
import com.itboye.sunsunhome.bean.AdBean;
import com.itboye.sunsunhome.util.AutoCloseDialog;
import com.itboye.sunsunhome.util.HttpRequest;
import com.itboye.sunsunhome.util.XImageLoader;
import com.itboye.sunsunhome.volley.MyJsonRequest;
import com.itboye.sunsunhome.volley.XErrorListener;
import com.itboye.sunsunhome.volley.XRequestListener;
import com.itboye.sunsunhome.www.aq.base.AqDateTime;
import com.itboye.sunsunhome.www.aq.base.AqDevice;
import com.itboye.sunsunhome.www.aq.base.AqDeviceInfo;
import com.itboye.sunsunhome.www.aq.base.AqDeviceMessage;
import com.itboye.sunsunhome.www.aq.base.MessageWhat;
import com.itboye.sunsunhome.www.aq.base.MyApplication;

/**
 * 日期：2015-04-30 1. 添加版本识别功能，支持AQ107、AQ209和AQ805设备 日期：2015-05-05 1. 添加手动添加设备功能
 */
@SuppressLint("NewApi")
public class DeviceActivity extends BaseActivity {
	int count = 0;
	int cnt = 0;
	MyApplication mApp;
	boolean mReadyExit;
	ListView mListView;
	Context mContext;
	AqDeviceInfo mSelectDeviceInfo;
	private ProgressDialog mProgressDialog;
	ImageView adImg;
	ImageView  back;
	RelativeLayout re_one, ad;
	ImageView cancel,imgAdd;
	RelativeLayout nodata;
	// 连接进度
	private final static int SUCCESS = 0;
	int progress = 0;

	RelativeLayout relyout, relyoutbg_wm, relyoutbg_wms;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_device);
		mApp = (MyApplication) getApplication();
		adImg = (ImageView) findViewById(R.id.adImg);
		imgAdd = (ImageView) findViewById(R.id.imgAdd);
		back = (ImageView) findViewById(R.id.back);
		cancel = (ImageView) findViewById(R.id.cancel);
		re_one = (RelativeLayout) findViewById(R.id.re_one);
		relyout = (RelativeLayout) findViewById(R.id.relyout);
		nodata = (RelativeLayout) findViewById(R.id.nodata);
		relyoutbg_wm = (RelativeLayout) findViewById(R.id.relyoutbg_wm);
		relyoutbg_wms = (RelativeLayout) findViewById(R.id.relyoutbg_wms);
		getAdImage();
		mContext = this;
		mApp.mDeviceUi = this;
		mReadyExit = false;
		mSelectDeviceInfo = null;
		mListView = (ListView) findViewById(R.id.device_listView);
		ad = (RelativeLayout) findViewById(R.id.ad);
		mProgressDialog = new ProgressDialog(this);

		mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				// TODO Auto-generated method stub
				// Cancel task.
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					mProgressDialog.dismiss();
				}
				return false;
			}
		});
		/**
		 * // mProgressDialog = ProgressDialog.show(DeviceActivity.this, //
		 * mSelectDeviceInfo.mDeviceName, "连接中，请稍后……"); // mProgressDialog = new
		 * ProgressDialog(MyApplication.context);
		 */
		// 列表项短按键处理
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mSelectDeviceInfo = mApp.mMyDeviceList.get(position);
				mApp.mEditDeviceInfo = mSelectDeviceInfo;
				mSelectDeviceInfo = mApp.mMyDeviceList.get(position);
				mProgressDialog.setTitle(mSelectDeviceInfo.mDeviceName);
				mProgressDialog.setMessage("连接中，请稍后...");
				mProgressDialog.show();
				System.out.println("countcounts" + progress);
				   final AutoCloseDialog d = new AutoCloseDialog(mProgressDialog);  
				   d.show(20000);
				
				new Thread(new Runnable() {
					@Override
					public void run() {
							mApp.mCurrentDevice = new AqDevice(
									mApp.mHandler, mApp.mDatabase,
									mApp.mPush.getClientID(),
									mSelectDeviceInfo);
							mApp.mCurrentDevice.asyncConnect();


					}
				}).start();
			}

		});
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				re_one.setVisibility(View.GONE);
				ad.setVisibility(View.GONE);
				relyoutbg_wm.setVisibility(View.GONE);
				if (mApp.mMyDeviceList.size() < 0) {
					relyoutbg_wm.setVisibility(View.VISIBLE);
				}

			}
		});
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		imgAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(DeviceActivity.this,
						AddDeviceNewActivity.class);
				startActivity(intent);
			}
		});

		// 列表项长按键处理
		mListView
				.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						mSelectDeviceInfo = mApp.mMyDeviceList.get(position);
						mApp.mEditDeviceInfo = mSelectDeviceInfo;
						Intent mainIntent = new Intent(DeviceActivity.this,
								EditDeviceActivity.class);
						DeviceActivity.this.startActivity(mainIntent);
						return true;
					}
				});
		refreshDeviceList();

		// 短信登录发送过来的广播
		IntentFilter filter1 = new IntentFilter("devicedio");
		registerReceiver(emailBroadcastReceiver, filter1);
	}


	BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			relyoutbg_wms.setVisibility(View.GONE);
		};
	};

	public void onSendRun() {
		// imgprocess.setVisibility(View.VISIBLE);
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					if (progress == 100) {// 图片上传完成
						// HandView.sendEmptyMessage(SUCCESS);
						return;
					}
					progress++;
					try {
						Thread.sleep(200); // 暂停0.2秒
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	/**
	 * 时间计时器
	 * 
	 * @param duration
	 * @return
	 */
	public static String timeParse(long duration) {
		String time = "";

		long minute = duration / 60000;
		long seconds = duration % 60000;

		long second = Math.round((float) seconds / 1000);

		if (minute < 10) {
			time += "0";
		}
		time += minute + ":";

		if (second < 10) {
			time += "0";
		}
		time += second;

		return time;
	}

	private void getAdImage() {
		// TODO Auto-generated method stub
		MyJsonRequest.Builder<List<AdBean>> builder = new MyJsonRequest.Builder<List<AdBean>>()
				.apiVer("100").typeKey("BY_Picture_getURL")
				.param("position", "6121")
				.requestListener(new XRequestListener<List<AdBean>>() {

					@Override
					public void onResponse(final List<AdBean> orderBean) {
						// onPullUpFinish(adapter, xlistview, orderBean);
						XImageLoader.load(orderBean.get(0).getImgUrl(), adImg);
						orderBean.get(0).getUrl();
						if (orderBean.get(0).getImgUrl() != null) {
							System.out.println("imgimgimg"
									+ orderBean.get(0).getImgUrl());
							adImg.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									Intent intent = new Intent(
											MyApplication.context,
											AqWebActivity.class);
									System.out.println(orderBean.get(0).getUrl());
									intent.putExtra("url",orderBean.get(0).getUrl());
									startActivity(intent);
								}
							});
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						Toast.makeText(DeviceActivity.this,
								exception + ":" + code + ":" + msg, 0).show();
					}
				});

		MyJsonRequest<List<AdBean>> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.menu_device, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.device_action_settings1) {
			// 一键配置
			Intent mainIntent = new Intent(DeviceActivity.this,
					SmartConfigActivity.class);
			DeviceActivity.this.startActivity(mainIntent);
			return true;
		}
		if (id == R.id.device_action_settings2) {
		
			// 添加局域网设备
			Intent mainIntent = new Intent(DeviceActivity.this,
					AddDeviceActivity.class);
			DeviceActivity.this.startActivity(mainIntent);
			return true;
		}
		if (id == R.id.device_action_settings3) {
			// 手动添加设备
			Intent mainIntent = new Intent(DeviceActivity.this,
					ManualAddDeviceActivity.class);
			DeviceActivity.this.startActivity(mainIntent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		// 如果是返回键
//		if (keyCode == KeyEvent.KEYCODE_BACK) {
//
//			// finish();
//			// mProgressDialog.setOnKeyListener(new
//			// DialogInterface.OnKeyListener() {
//			//
//			// public boolean onKey(DialogInterface dialog, int keyCode,
//			// KeyEvent event) {
//			// // TODO Auto-generated method stub
//			// // Cancel task.
//			// if (keyCode == KeyEvent.KEYCODE_BACK) {
//			// mProgressDialog.dismiss();
//			// }
//			// return true;
//			// }
//			// });
//			// onStop();
//			System.out.println("执行了");
//			// if (!mReadyExit) {
//			// mReadyExit = true;
//			// Toast.makeText(mContext, "再按一次返回键退出", Toast.LENGTH_SHORT)
//			// .show();
//			// // 延时恢复
//			// new Handler().postDelayed(new Runnable() {
//			// public void run() {
//			// mReadyExit = false;
//			// }
//			// }, 3000);
//			// } else {
//			// mReadyExit = false;
//			// System.exit(0);
//			// }
//			return false;
//		}
//		return super.onKeyDown(keyCode, event);
//	}

	public void refreshDeviceList() {
		mListView.setVisibility(View.VISIBLE);
		relyout.setVisibility(View.VISIBLE);
		nodata.setVisibility(View.GONE);
		ArrayList<HashMap<String, Object>> listItems = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < mApp.mMyDeviceList.size(); i++) {
			AqDeviceInfo deviceInfo = mApp.mMyDeviceList.get(i);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemName", deviceInfo.mDeviceName);
			map.put("ItemDid", "DID : " + deviceInfo.mDid);
			map.put("ItemState1", "");
			map.put("ItemState2", "");
			map.put("ItemRightArrow", R.drawable.ic_right_arrow);
			listItems.add(map);
		}
		SimpleAdapter listItemsAdapter = new SimpleAdapter(this, listItems,
				R.layout.device_item, new String[] { "ItemName", "ItemDid",
						"ItemState1", "ItemState2", "ItemRightArrow" },
				new int[] { R.id.textView_dev_name, R.id.textView_dev_did,
						R.id.textView_dev_state1, R.id.textView_dev_state2,
						R.id.imageView_dev_right_arrow });
		mListView.setAdapter(listItemsAdapter);
		System.out.println("listItems" + listItems);
		System.out.println("listItemsssss" + mApp.mMyDeviceList.size());
		if (mApp.mMyDeviceList.size() <= 0) {
			relyout.setVisibility(View.GONE);
			nodata.setVisibility(View.VISIBLE);
			relyoutbg_wm.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
			relyoutbg_wms.setVisibility(View.VISIBLE);
		} else {
			relyout.setVisibility(View.VISIBLE);
			nodata.setVisibility(View.GONE);
			relyoutbg_wm.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
			relyoutbg_wms.setVisibility(View.GONE);
		}
	}

	private void connectFailedProcess() {

		try {
			if (mApp.mCurrentDevice != null) {
				if (mApp.mCurrentDevice.mInitState == false) {
					if (count > 3) {
						mProgressDialog.dismiss();
						count = 0;
						if (mApp.mCurrentDevice != null) {
							mApp.mCurrentDevice.closeConnect();
						}
						Toast.makeText(mContext, "连接设备失败", Toast.LENGTH_SHORT)
								.show();
					} else {
						// 连接线程
						new Thread(new Runnable() {
							@Override
							public void run() {
								mApp.mCurrentDevice = new AqDevice(
										mApp.mHandler, mApp.mDatabase,
										mApp.mPush.getClientID(),
										mSelectDeviceInfo);
								mApp.mCurrentDevice.asyncConnect();

							}
						}).start();
					}
				}
			}
		} catch (Exception e) {
		}
	}

	public void newMessage(Message msg) {
		if (msg.what == MessageWhat.DeviceMessage) {
			AqDeviceMessage msgObj = (AqDeviceMessage) msg.obj;
			switch (msgObj.mMessageType) {
			case GetVersionOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							switch (mApp.mCurrentDevice.mDeviceInfo.mDeviceType) {
							case AQ107:
							case AQ209:
							case AQ208:
							case AQ211:
								// mApp.mCurrentDevice.linuxReboot();// 重启设备
								mProgressDialog.setMessage("版本获取成功，正在读取状态……");
								mApp.mCurrentDevice.getState();
								break;
							case AQ805:
								// mApp.mCurrentDevice.linuxReboot();// 重启设备
								mProgressDialog.setMessage("版本获取成功，正在获取订阅令牌……");
								mApp.mCurrentDevice.getSubscribeToken(true,
										true, true);
								break;
							default:
								connectFailedProcess();
								break;
							}
						}
					}
				} catch (Exception e) {
				}
				break;
			case GetVersionFailed:
				connectFailedProcess();
				break;
			case GetStateOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							mProgressDialog.setMessage("读取状态成功，正在同步日期时间……");
							mApp.mCurrentDevice.setDateTime(new AqDateTime());
						}
					}
				} catch (Exception e) {
				}
				break;
			case SetDatetimeOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							mApp.mCurrentDevice.mInitState = true;
							// 初始化完成，进入设备控制界面
							mProgressDialog.dismiss();
							Intent mainIntent = new Intent(DeviceActivity.this,
									DeviceConsoleActivity.class);
							DeviceActivity.this.startActivity(mainIntent);
						}
					}
				} catch (Exception e) {
				}
				break;
			case SetDatetimeFailed:
				connectFailedProcess();
				break;
			case GetSubscribeTokenFailed:
				connectFailedProcess();
				break;
			case GetSubscribeTokenOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							mProgressDialog.setMessage("读取订阅令牌成功，正在读取状态……");
							mApp.mCurrentDevice.getState();
						}
					}
				} catch (Exception e) {
				}
				break;
			case GetStateFailed:
				connectFailedProcess();
				break;
			case ConnectOk:
				try {
					if (mApp.mCurrentDevice != null) {
						if (mApp.mCurrentDevice.mInitState == false) {
							mProgressDialog.setMessage("连接成功，获取设备版本……");
							mApp.mCurrentDevice.getDeviceVersion();
						}
					}
				} catch (Exception e) {
				}
				break;
			case ConnectFailed:
				connectFailedProcess();
				break;
			default:
				break;
			}
		}
	}

	protected void onStop() {
		mProgressDialog.dismiss();
		super.onStop();
	}
}
